'''
# -*- coding: utf-8 -*-
from django.template import RequestContext
from django.http import HttpResponse,HttpResponseRedirect,HttpResponseBadRequest
from django.core.urlresolvers import reverse
from django.shortcuts import render_to_response,redirect,render, get_object_or_404
from django.views.decorators.csrf import csrf_exempt
from django.utils.encoding import smart_str
from django.contrib import auth, messages
from django.contrib.auth.models import User, Group
from django.contrib.auth.decorators import login_required
from wechat_sdk.exceptions import ParseError
from wechat_sdk.messages import (
    TextMessage, VoiceMessage, ImageMessage, VideoMessage, LinkMessage, LocationMessage, EventMessage, ShortVideoMessage
)
import sys,hashlib,logging,uuid,json,os,traceback,time, random, string, requests
from account.models import *
from disn.utilities import *
from decimal import Decimal, getcontext
from django.contrib.auth.models import User, Group
from django.contrib import auth, messages
from django.contrib.auth.decorators import login_required
from disn.settings import get_wechat_instance, WECHAT_ADMIN_USER_ID, BASE_DIR, DISN_HTTP_URL, mc, APPID, DEBUG
from taskqueue.tasks import send_user_consult_notification
from urllib.parse import unquote, quote

log = logging.getLogger(__name__)
log.setLevel(logging.INFO)

adminuser =  mc.get('disn_adminuser')
if not adminuser:
    try:
        adminuser = User.objects.get(username=WECHAT_ADMIN_USER_ID)
        mc.set(key='disn_adminuser', val=adminuser, time=43200)
    except User.DoesNotExist:
        log.error('user %s not found' % WECHAT_ADMIN_USER_ID)

def demo(request):
    return render(request, 'wechat.demo.html', {'signature': mc.get('disn_signature') ,'timestamp':mc.get('disn_timestamp') ,'nonce':mc.get('disn_nonce')})

def contactus(request):
    return render(request, 'wechat.contactus.html')

def article(request,id):
    log.info("function article reload.")
    try:
        int(id)
        news = get_object_or_404(News, pk=id)
    except ValueError:
        url = id
        news = get_object_or_404(News, abbreviated_name=id)
    return render(request,'wechat.article.html',{'category':news.category,'news':news})

def checkSignature(request):
    global TOKEN
    signature = request.GET.get("signature", None)
    timestamp = request.GET.get("timestamp", None)
    nonce = request.GET.get("nonce", None)
    echoStr = request.GET.get("echostr",None)
    token = TOKEN
    tmpList = [token,timestamp,nonce]
    tmpList.sort()
    tmpstr = "%s%s%s" % tuple(tmpList)
    tmpstr = hashlib.sha1(tmpstr).hexdigest()
    if tmpstr == signature:
        return echoStr
    else:
        return None

@csrf_exempt
def greetings(request):
    log.info ('function greetings reload')
    wechat = get_wechat_instance()
    employee_list = UserProfile.objects.filter(category='5') # for test use only
    for employee in employee_list:
        print (employee.openid, employee.truename, employee.nickname)
        try:
            wechat.send_text_message(employee.openid,'%s,你好！如果你收到此消息，请回复一下"OK"。谢谢！' % employee.nickname)
        except:
            notify_admin(user=employee, body='系统出错啦！', leave_msg='发送消息失败，可能是用户取消关注。\n%s\n%s' %(employee.openid,employee.nickname), remark='')
    return HttpResponse('done')

def get_user_consulting_params(user,body,leave_msg,remark):
    if user:
        user_name = user.truename
        user_company = user.school
        user_mobile = user.mobile
    else:
        user_name = 'None'
        user_company = 'None'
        user_mobile = 'None'
    params = {
        'first': {
            # 'value':'您有客户留言，请尽快回复!',
            'value': body,
            'color':'#173177'
        },
        'Name': {
            'value':user_name,
            'color':'#173177'
        },
        'Company': {
            'value':user_company,
            'color':'#173177'
        },
        'Phone': {
            'value':user_mobile,
            'color':'#173177'
        },
        'LeaveMessage': {
            'value':leave_msg,
            'color':'#173177'
        },
        'ProductName': {
            'value':user.currency_subscribed,
            'color':'#173177'
        },
        'remark': {
            # 'value':'点击这里立即回复客户',
            'value':remark,
            'color':'#173177'
        }
    }
    return params

def notify_rm(user,body,leave_msg,remark):
    if user.owner.username == 'admin':
        try:
            rm = User.objects.get(username='jezhang')
            rm = rm.profile
        except User.DoesNotExist:
            log.error('user jezhang not found')
    else:
        rm = user.owner.profile
    try:
        send_template_message(user_id=rm.openid,template_id='B5BFLVC8M69rf7tmtaKJLGkGBKqpOoIZxB03inMBoVg',data=get_user_consulting_params(user=user,body=body,leave_msg=leave_msg,remark=remark),url='%s/account/wechat/reply/user/%s/' %(disn_HTTP_URL,str(user.id)),topcolor='#FF0000')
        receive_log = WechatLog()
        receive_log.user = rm
        receive_log.content = leave_msg
        receive_log.msg_type = '1'
        receive_log.save()
    except BaseException as e:
        logging.exception(e)


def notify_admin(user,body,leave_msg,remark): # send to jezhang wechat account
    adminuser =  mc.get('disn_adminuser')
    if adminuser :
        try:
            send_template_message(user_id=adminuser.profile.openid,template_id='B5BFLVC8M69rf7tmtaKJLGkGBKqpOoIZxB03inMBoVg',data=get_user_consulting_params(user,body=body,leave_msg=leave_msg,remark=remark),url='%s/wx/reply/user/%s/' %(disn_HTTP_URL,str(user.id)),topcolor='#FF0000')
            receive_log = WechatLog()
            receive_log.user = adminuser
            receive_log.content = leave_msg
            receive_log.msg_type = '1'
            receive_log.save()
        except BaseException as e:
            logging.exception(e)

def send_article_message(openid,msg):
    wechat = get_wechat_instance()
    wechat.send_article_message(openid,msg)

def send_text_message(openid,content):
    wechat = get_wechat_instance()
    wechat.send_text_message(openid,content)

def get_template_id_by_short_id(template_id_short):
    wechat = get_wechat_instance()
    return wechat.get_template_id(template_id_short)['template_id']

def send_template_message(user_id, template_id, data, url, topcolor):
    wechat = get_wechat_instance()
    wechat.send_template_message(user_id=user_id,template_id=template_id,data=data,url=url,topcolor=topcolor)

def get_and_save_download_media(media_id,path):
    wechat = get_wechat_instance()
    resp = wechat.download_media(media_id)
    with open(path, 'wb') as fd:
        for chunk in resp.iter_content(1024):
            fd.write(chunk)

def get_message_prompt(forced_update=False):
    if forced_update:
        message_set = Config.objects.filter(status='1',category='3')
        message_prompt = {}
        for msg in message_set:
            message_prompt[msg.key] = msg.value
        mc.set('disn_message_prompt',message_prompt)
    else:
        message_prompt = mc.get('disn_message_prompt')
        if not message_prompt:
            message_prompt = {}
            message_set = Config.objects.filter(status='1',category='3')
            for msg in message_set:
                message_prompt[msg.key] = msg.value
            mc.set('disn_message_prompt',message_prompt)
    return message_prompt

def get_recently_news_msgs(forced_update=False):
    if forced_update:
        recently_news = Config.objects.filter(status='1',category='1').order_by('-datetime_created')[:5]
        mc.set('disn_recently_news',recently_news)
    else:
        recently_news = mc.get('disn_recently_news')
        if not recently_news:
            recently_news = Config.objects.filter(status='1',category='1').order_by('-datetime_created')[:5]
            mc.set('disn_recently_news',recently_news)
    news_list = []
    for news in recently_news:
        if news.value.find('|') > 0:
            temp_array = news.value.split('|')
            article_url = temp_array[0]
            pic_url = temp_array[1]
        else:
            article_url = news.value
            pic_url = ''
        news_list.append(
            {
                'title':news.key,
                'description':news.remark,
                'picurl':pic_url,
                'url':article_url,
            }
        )
    return news_list

@csrf_exempt
def get_signature(request):
    url = request.POST.get('url')
    print ('%s():%s' %(request.method, url))
    return HttpResponse(json.dumps(get_jssdk_signature(request)), content_type="application/json")

def get_jssdk_signature(request):
    if DEBUG:
        return None
    wechat = get_wechat_instance()
    jsapi_ticket = wechat.get_jsapi_ticket()['jsapi_ticket']
    # print('jsapi_ticket=%s' %jsapi_ticket)
    nonce_str= ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(15))
    # print('noncestr=%s' %nonce_str)
    timestamp_int = int(time.time())
    # print('timestamp=%d' %timestamp_int)
    # url = 'http://' + request.META.get('HTTP_HOST')+request.META.get('PATH_INFO')+request.META.get('QUERY_STRING','')
    url = 'https://' + request.META.get('HTTP_HOST')+request.META.get('PATH_INFO')
    # print('url=%s' %url)
    tmpstr = 'jsapi_ticket=%s&noncestr=%s&timestamp=%d&url=%s' %(jsapi_ticket,nonce_str,timestamp_int,url)
    tmpstr = tmpstr.encode('utf-8') # python3 need this line
    tmpstr = hashlib.sha1(tmpstr).hexdigest() # verify at http://mp.weixin.qq.com/debug/cgi-bin/sandbox?t=jsapisign
    # print('signature=%s' %tmpstr)
    jssdk_signature = {}
    jssdk_signature['timestamp']  = timestamp_int
    jssdk_signature['nonce'] = nonce_str
    jssdk_signature['signature'] = tmpstr
    jssdk_signature['appid'] = APPID
    return jssdk_signature

def jssdk_demo(request):
    return render(request, 'weui/weixin-jssdk.html', {'jssdk_signature':get_jssdk_signature(request)})

@login_required
def reply_user(request,id):
    user = get_object_or_404(UserProfile,id=id)
    try:
        management_team = Group.objects.get(name='management-team')
    except Group.DoesNotExist:
        management_team = Group(name="management-team")
        management_team.save()
    if request.user.groups.filter(name=management_team.name).count() < 1 and user.owner != request.user:
        messages.add_message(request, messages.WARNING, '您没有权限向客户[%s]发送消息' % user.truename)
        return render(request,'wechat.reply.html')
    if request.method == 'POST':
        openid = request.POST.get('openid')
        content = request.POST.get('content',None)
        if content is None or content == '':
            messages.add_message(request, messages.WARNING, '您没有输入任何内容!请重新输入')
        else:
            send_text_message(openid,content)
            reply_log = WechatLog()
            reply_log.content = content
            reply_log.user = user
            reply_log.msg_type = '2'
            reply_log.save()
            messages.add_message(request, messages.INFO, '成功发送消息给客户!')
        # return redirect(reverse('weixin.views.reply_user',args=(str(id))))
        return redirect('/wx/reply/user/%s/' %str(id))
        # return HttpResponse('已回复成功!')
    else: # GET request
        wechatlog_set = user.wechatlog_set.all()
        if not wechatlog_set:
            wechatlog_set = None
        return render(request,'weui/wechat.reply.html', {'user':user,'wechatlog_set':wechatlog_set})

def print_user_info_json(user_info_json):
    print (user_info_json)
    # for (k,v) in user_info_json.items():
    #     print '%s: %s' %(k,v)

@csrf_exempt
def save_followers(request):
    wechat = get_wechat_instance()
    existed_openids = UserProfile.get_existed_wechat_openid()
    follower_json = wechat.get_followers()
    followers = follower_json['data']['openid']
    cnt = 0
    for _openid in followers:
        if not _openid in existed_openids and _openid != 'oFOmtwf_rCN4Riaku9zLDYLMA-tg':
            print ('[%s] not existed.' % _openid)
            new_user_info_json = wechat.get_user_info(_openid)
            UserProfile.get_create_or_update_user(new_user_info_json, 'subscribe')
            cnt += 1
    followers_list_str = '\n'.join(followers)
    return HttpResponse('Successfully saved [%d] followers!' %cnt)

@csrf_exempt
def portal(request):
    log.info('function portal(request) reload')
    wechat = get_wechat_instance()
    echostr = request.GET.get('echostr',None)
    if echostr is not None and echostr != '':
        print ('Start checking signature...')
        signature = request.GET.get('signature')
        msg_signature = request.GET.get('msg_signature')
        timestamp = request.GET.get('timestamp')
        nonce = request.GET.get('nonce')
        if not wechat.check_signature(signature=signature, timestamp=timestamp, nonce=nonce):
            print ('Verify Failed')
            return HttpResponseBadRequest('Verify Failed')
        else:
            print ('Verify Success')
            return HttpResponse(echostr,content_type="text/plain")
    else:
        msg_signature = request.GET.get('msg_signature')
        timestamp = request.GET.get('timestamp')
        nonce = request.GET.get('nonce')
    xml = request.body
    try:
        wechat.parse_data(data=xml, msg_signature=msg_signature, timestamp=timestamp, nonce=nonce)
    except ParseError:
        return HttpResponseBadRequest('Invalid XML Data')
    message = wechat.get_message()  # 获取解析好的微信请求信息
    wx_openid = message.source
    user_info_json = mc.get(str(wx_openid))
    print ('=' * 32 + 'New Message from [%s], message.type:%s' %(wx_openid,message.type) + '=' * 33)
    if isinstance(message,TextMessage):
        print ("message.content: %s" %message.content)
    if isinstance(message, EventMessage):
        if message.type == 'click':
            print ("message.key: %s" %message.key)
    if not user_info_json:
        user_info_json = wechat.get_user_info(wx_openid, lang='zh_CN')
        user = UserProfile.get_create_or_update_user(user_info_json,message.type,True)
        print ('<<<<<fetch user_info_json from wechat server(call function get_user_info())>>>>>')
        if message.type != 'unsubscribe':
            mc.set(key=str(wx_openid), val=user_info_json)
    else:
        print ('<<<<<fetch user_info_json from memcache server>>>>>')
        user = UserProfile.get_create_or_update_user(user_info_json,message.type,False)
    print_user_info_json(user_info_json)

    print ('=' * 131)
    if message.type == 'unsubscribe':
        mc.delete(str(wx_openid))
    response = None
    reply_msg = receive_msg = ''

    if user is None:
        return HttpResponse('unsubscribe')
    save_path = './media/wechat/attachments/%s/' % user.id
    link_path = None
    file_name = sid()
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    # message_prompt = get_message_prompt()
    if isinstance(message, TextMessage):
        receive_text = message.content.strip()
        if user.user.is_active and user.category == '0' and user.user.is_superuser:
            if receive_text == 'update_menu':
                try:
                    config = WxConfig.objects.get(status='1',category='4',key='menu')
                    wechat.create_menu(eval(config.value))
                    response = wechat.response_text(content='微信菜单更新成功！')
                except WxConfig.DoesNotExist:
                    response = wechat.response_text('未找到微信菜单定义变量[menu]')
            elif message.content.lower() == 'not_subscribed':
                existed_openids = UserProfile.get_existed_wechat_openid()
                follower_json = wechat.get_followers()
                followers = follower_json['data']['openid']
                not_subscribed_list = []
                for _openid in existed_openids:
                    if not _openid in followers:
                        not_subscribed_customer = UserProfile.get_customer_by_openid(_openid)
                        if not_subscribed_customer:
                            not_subscribed_list.append('%s:(%s)' %(not_subscribed_customer.nickname, _openid))
                        else:
                            not_subscribed_list.append('Unknow name:(%s)' %_openid)
                response = wechat.response_text('\n'.join(not_subscribed_list))
            elif message.content.lower() == 'get_followers':
                existed_openids = UserProfile.get_existed_wechat_openid()
                follower_json = wechat.get_followers()
                followers = follower_json['data']['openid']
                for _openid in followers:
                    if not _openid in existed_openids and _openid != 'oFOmtwf_rCN4Riaku9zLDYLMA-tg':
                        print( '[%s] not existed.' % _openid)
                        new_user_info_json = wechat.get_user_info(_openid, lang='zh_CN')
                        # print str(new_user_info_json)
                        UserProfile.get_create_or_update_user(new_user_info_json, 'subscribe')
                followers_list_str = '\n'.join(followers)
                # print followers_list_str
                response = wechat.response_text(followers_list_str)
            else:
                try:
                    config = WxConfig.objects.get(key='admin_%s' %receive_text,status='1',category='3')
                    # response = wechat.response_text(config.value)
                    if config.reply_type == 'text':
                        reply_msg = config.value
                        response = wechat.response_text(content=reply_msg)
                    elif config.reply_type == 'news':
                        # reply_msg = '发送[%s]卡片' %config.key
                        response = wechat.response_news(eval(config.value))
                    else: # 默认发送文本
                        reply_msg = config.value
                        response = wechat.response_text(content=reply_msg)

                except WxConfig.DoesNotExist:
                    config = WxConfig()
                    config.key = 'admin_%s' %receive_text
                    config.value = 'admin_%s' %receive_text
                    config.status = '1'
                    config.category = '3'
                    config.save()
                    response = wechat.response_text('新建微信自定义字符串[%s]' %config.key)
        else:
            try:
                config = WxConfig.objects.get(key=receive_text,status='1',category='3')
            except WxConfig.DoesNotExist:
                items = Item.query_top_items_by(receive_text, 6)
                if items and len(items) > 0:
                    content_list = []
                    content_header = {}
                    content_header['title'] = '[%s]查询结果' % receive_text
                    try:
                        banner_config = WxConfig.objects.get(key='SEARCH-BANNER', status='1', category='3')
                    except WxConfig.DoesNotExist:
                        banner_config = WxConfig()
                        banner_config.key = 'SEARCH-BANNER'
                        banner_config.status = '1'
                        banner_config.category = '3'
                        banner_config.value = 'https://img.ztm.me/2018/01/search.jpg'
                        banner_config.save()
                    content_header['picurl'] = banner_config.value
                    content_list.append(content_header)
                    for item in items:
                        content_body = {}
                        content_body['title'] = item.article_title
                        content_body['picurl'] = 'http:%s' %item.qiniu_pic
                        content_body['url'] = 'https://www.ztm.me/youhui/detail/%s/' % item.pk
                        content_list.append(content_body)
                    content_list_json = json.dumps(content_list)
                    # response = wechat.response_news(eval(content_list_json))
                    # return HttpResponse(response)
                    config = WxConfig()
                    config.reply_type = 'news'
                    config.value = content_list_json
                else:
                    try:
                        config = WxConfig.objects.get(key='auto_reply_text',status='1',category='3')
                    except WxConfig.DoesNotExist:
                        config = WxConfig()
                        config.key = 'auto_reply_text'
                        config.value = '我们已经收到您的留言。'
                        config.status = '1'
                        config.category = '3'
                        config.save()
            receive_msg = '%s(%s)' %(receive_text,message.type)
            if config.reply_type == 'text':
                reply_msg = config.value
                response = wechat.response_text(content=reply_msg)
            elif config.reply_type == 'news':
                # reply_msg = '发送[%s]卡片' %config.key
                response = wechat.response_news(eval(config.value))
            else: # 默认发送文本
                reply_msg = config.value
                response = wechat.response_text(content=reply_msg)
    elif isinstance(message, VoiceMessage):
        receive_text = message.recognition
        try:
            config = WxConfig.objects.get(key=receive_text, status='1', category='3')
        except WxConfig.DoesNotExist:
            try:
                config = WxConfig.objects.get(key='auto_reply_voice',status='1',category='3')
            except WxConfig.DoesNotExist:
                config = WxConfig()
                config.key = 'auto_reply_voice'
                config.value = '我们已经收到您的语音留言。'
                config.status = '1'
                config.category = '3'
                config.save()
        receive_msg = '%s(%s)' %(receive_text, message.type)
        reply_msg = config.value
        response = wechat.response_text(content=reply_msg)
        resp = wechat.download_media(message.media_id)
        save_path = '%s%s.%s' %(save_path,file_name,message.format)
        link_path = './wechat/attachments/%s/' % user.id
        link_path = '%s%s.amr' %(link_path,file_name)
        log.info('save_path=%s' %save_path) # file_path=./wechat/attachments/jezhang/150611114353137791.jpg
        with open(save_path, 'wb') as fd:
            for chunk in resp.iter_content(1024):
                fd.write(chunk)
    elif isinstance(message, ImageMessage):
        try:
            config = WxConfig.objects.get(key='auto_reply_image',status='1',category='3')
        except WxConfig.DoesNotExist:
            config = WxConfig()
            config.key = 'auto_reply_image'
            config.value = '我们已经收到您的图片。'
            config.status = '1'
            config.category = '3'
            config.save()
        reply_msg = config.value
        response = wechat.response_text(content=reply_msg)
        receive_msg = '收到图片(%s)' %message.type
        resp = wechat.download_media(message.media_id)
        save_path = '%s%s.jpg' %(save_path,file_name)
        link_path = './wechat/attachments/%s/' % user.id
        link_path = '%s%s.jpg' %(link_path,file_name)
        log.info('save_path=%s' %save_path)
        with open(save_path, 'wb') as fd:
            for chunk in resp.iter_content(1024):
                fd.write(chunk)
    elif isinstance(message, VideoMessage):
        try:
            config = WxConfig.objects.get(key='auto_reply_video',status='1',category='3')
        except WxConfig.DoesNotExist:
            config = WxConfig()
            config.key = 'auto_reply_video'
            config.value = '我们已经收到您的视频。'
            config.status = '1'
            config.category = '3'
            config.save()
        reply_msg = config.value
        response = wechat.response_text(content=reply_msg)
        receive_msg = '收到视频(%s)' %message.type
        resp = wechat.download_media(message.media_id)
        save_path = '%s%s.mp4' %(save_path,file_name)
        link_path = './wechat/attachments/%s/' % user.id
        link_path = '%s%s.mp4' %(link_path,file_name)
        log.info('save_path=%s' %save_path)
        with open(save_path, 'wb') as fd:
            for chunk in resp.iter_content(1024):
                fd.write(chunk)
    elif isinstance(message, ShortVideoMessage):
        try:
            config = WxConfig.objects.get(key='auto_reply_short_video',status='1',category='3')
        except WxConfig.DoesNotExist:
            config = WxConfig()
            config.key = 'auto_reply_short_video'
            config.value = '我们已经收到您的短视频。'
            config.status = '1'
            config.category = '3'
            config.save()
        reply_msg = config.value
        response = wechat.response_text(content=reply_msg)
        receive_msg = '收到短视频(%s)' %message.type
        resp = wechat.download_media(message.media_id)
        save_path = '%s%s.mp4' %(save_path,file_name)
        link_path = './wechat/attachments/%s/' % user.id
        link_path = '%s%s.mp4' %(link_path,file_name)
        log.info('save_path=%s' %save_path)
        with open(save_path, 'wb') as fd:
            for chunk in resp.iter_content(1024):
                fd.write(chunk)
    # elif isinstance(message, LinkMessage):
    #     reply_msg = '我们已经收到您的链接。\n谢谢，祝您生活愉快!'
    #     response = wechat.response_text(content=reply_msg)
    #     receive_msg = '链接消息(%s)' %message.type
    # elif isinstance(message, LocationMessage):
    #     reply_msg = '我们已经收到您的地理位置。\n谢谢，祝您生活愉快!'
    #     response = wechat.response_text(content=reply_msg)
    #     receive_msg = '地理位置消息(%s)' %message.type
    elif isinstance(message, EventMessage):  # 事件信息
        if message.type == 'subscribe':
            try:
                config = WxConfig.objects.get(key='auto_reply_subscribe', category='3', reply_type='text')
            except WxConfig.DoesNotExist:
                config = WxConfig()
                config.key = 'auto_reply_subscribe'
                config.value = '尊敬的%s，感谢关注我们！'
                config.status = '1'
                config.category = '3'
                config.save()
            reply_msg = config.value % user.nickname
            if config.status == '1':
                wechat.send_text_message(wx_openid,reply_msg)
            try:
                config = WxConfig.objects.get(key='auto_reply_subscribe_card', category='3', reply_type='news')
            except WxConfig.DoesNotExist:
                config = WxConfig()
                config.key = 'auto_reply_subscribe_card'
                config.value = None
                config.status = '0'
                config.category = '3'
                config.reply_type = 'news'
                config.save()
            if config.status == '1':
                response = wechat.response_news(eval(config.value))
            receive_msg = '新用户关注事件(%s)' %message.type
        elif message.type == 'unsubscribe':
            receive_msg = '用户取消关注事件(%s)' %message.type
        # elif message.type == 'scan':
        #     reply_msg = '我们已经收到您的二维码扫描事件'
        #     response = wechat.response_text(content=reply_msg)
        #     receive_msg = '用户二维码扫描事件(%s)' %message.type
        # elif message.type == 'location':
        #     reply_msg = '我们已经收到您上报地理位置事件'
        #     response = wechat.response_text(content=reply_msg)
        #     receive_msg = '用户上报地理位置事件(%s)' %message.type
        elif message.type == 'click':
            if message.key == "KEFUONLINE":
                hour = datetime.datetime.now().hour
                receive_msg = '用户请求人工客服(%s|%s)' %(message.type,message.key)
                if hour >= 9 and hour <= 18:
                    response = wechat.group_transfer_message() # 会话转给客服
                else:
                    try:
                        config = WxConfig.objects.get(key='auto_kefu_offline',status='1',category='3')
                    except WxConfig.DoesNotExist:
                        config = WxConfig()
                        config.key = 'auto_kefu_offline'
                        config.value = '在线客服上班时间为早上9点到下午17点'
                        config.status = '1'
                        config.category = '3'
                        config.save()
                    reply_msg = config.value
                    response = wechat.response_text(content=reply_msg)
            elif message.key == 'LATEST_NEWS':
                response = wechat.response_news(get_recently_news_msgs())
                receive_msg = '用户请求近期文章(%s|%s)' %(message.type,message.key)
            else:
################################################################################
                try:
                    config = WxConfig.objects.get(key=message.key,status='1',category='3')
                except WxConfig.DoesNotExist:
                    try:
                        config = WxConfig.objects.get(key=message.key,status='1',category='3')
                    except WxConfig.DoesNotExist:
                        config = WxConfig()
                        config.key = message.key
                        config.value = '请设置响应内容'
                        config.status = '1'
                        config.category = '3'
                        config.save()
                receive_msg = '%s(%s)' %(message.key,message.type)
                if config.reply_type == 'text':
                    reply_msg = config.value
                    response = wechat.response_text(content=reply_msg)
                elif config.reply_type == 'news':
                    # reply_msg = '发送[%s]卡片' %config.key
                    response = wechat.response_news(eval(config.value))
                else: # 默认发送文本
                    reply_msg = config.value
                    response = wechat.response_text(content=reply_msg)
################################################################################
        elif message.type == 'view':
            receive_msg = '用户请求页面事件(%s|%s)' %(message.type,message.key)
        elif message.type == 'templatesendjobfinish':
            receive_msg = None
        elif message.type == 'kf_create_session':
            receive_msg = '进入客服会话模式(%s)' %message.type
        elif message.type == 'kf_close_session':
            receive_msg = '退出客服会话模式(%s)' %message.type
        else:
            receive_msg = '用户触发未知类型事件(%s)' %message.type
    else:
        try:
            config = WxConfig.objects.get(key='auto_kefu_offline',status='1',category='3')
        except WxConfig.DoesNotExist:
            config = WxConfig()
            config.key = 'auto_kefu_offline'
            config.value = '我们已经收到您的未知类型文件。\n谢谢，祝您生活愉快!'
            config.status = '1'
            config.category = '3'
            config.save()
        reply_msg = config.value
        response = wechat.response_text(content=reply_msg)
        receive_msg = '未知类型(%s)' %message.type
    if receive_msg:
        # notify admin
        if user.user.is_active and not user.user.is_staff:
            send_user_consult_notification.delay(wechat=wechat, first='微信用户操作提醒', username=user_info_json.get('nickname',wx_openid), content=receive_msg, remark=None, url=None)
        receive_log = WechatLog()
        receive_log.content = receive_msg
        receive_log.user = user
        receive_log.msg_type = '1'
        if link_path:
            receive_log.attachment = link_path
        receive_log.save()
        # notify_rm(user=user, body='您有客户留言，请尽快回复!', leave_msg=receive_msg, remark='点击这里立即回复客户')
    return HttpResponse(response)
'''